package com.fujimana.rockincat.restree.phase;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.fujimana.rockincat.restree.context.ApplicationContext;
import com.fujimana.rockincat.restree.context.Context;
import com.fujimana.rockincat.restree.context.PhaseContext;
import com.fujimana.rockincat.restree.context.RequestContext;
import com.fujimana.rockincat.restree.web.RestContextFactory;

public class ContextInitializePahse implements Phase {
	
	@Override
	public void execute(Map<String, Object> context) {
		
		HttpServletRequest request = (HttpServletRequest) context.get(HttpServletRequest.class.getName());
		
		Context rstCtx = RestContextFactory.getInstance().create(
				new ApplicationContext(request.getSession(true).getServletContext()),
				new RequestContext(request),
				new PhaseContext());
		
		context.put(Context.class.getName(), rstCtx);
		Contexts.setCurrentInstance(rstCtx);
		
		request.getSession().invalidate();
	}

	@Override
	public String getId() {
		return ContextInitializePahse.class.getSimpleName();
	}

	@Override
	public boolean isChain() {
		return true;
	}
	
	static public class Contexts {

		private static ThreadLocal<Context> instance = new ThreadLocal<Context>() {
			protected Context initialValue() {
				return null;
			}
		};

		public static Context getCurrentInstance() {
			return instance.get();
		}

		protected static void setCurrentInstance(Context context) {
			if (context == null) {
				instance.remove();
			} else {
				instance.set(context);
			}

		}

	}
	
}
